<script setup lang="ts">
import { ref, onMounted, reactive, h } from 'vue';
import { useRouter } from 'vue-router';
import { 
  Card, Table, Button, Input, Space, 
  message, Modal, Form, Tag, Tooltip 
} from 'ant-design-vue';
import { 
  SearchOutlined, 
  EditOutlined, 
  DeleteOutlined, 
  StarOutlined,
  StarFilled,
} from '@ant-design/icons-vue';
import { listAppVoByPageByAdmin, deleteApp, updateAppByAdmin } from '@/api/appController';
import { useUserStore } from '@/stores/user';

const router = useRouter();
const userStore = useUserStore();
const formRef = ref();

// 表格数据和加载状态
const dataSource = ref<API.AppVO[]>([]);
const loading = ref(false);
const total = ref(0);
const pagination = reactive({
  current: 1,
  pageSize: 10,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '50', '100'],
});

// 搜索参数
const searchParams = reactive({
  appName: '',
  userId: undefined,
});

// 设置精选对话框
const setFeaturedVisible = ref(false);
const currentApp = ref<API.AppVO | null>(null);
const priorityForm = reactive({
  priority: 0,
});
const submitLoading = ref(false);

// 检查是否管理员
onMounted(() => {
  if (userStore.loginUser.userRole !== 'admin') {
    message.error('您没有权限访问此页面');
    router.push('/');
    return;
  }
  
  // 初始加载数据
  loadData();
});

// 加载应用列表数据
const loadData = async () => {
  loading.value = true;
  try {
    const params: API.AppQueryRequest = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      appName: searchParams.appName || undefined,
      userId: searchParams.userId
    };
    
    const res = await listAppVoByPageByAdmin(params);
    if (res.data?.code === 0 && res.data?.data) {
      dataSource.value = res.data.data.records || [];
      total.value = res.data.data.totalRow || 0;
    } else {
      message.error(res.data?.message || '获取应用列表失败');
    }
  } catch (error) {
    console.error('获取应用列表失败', error);
    message.error('获取应用列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理表格分页变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  loadData();
};

// 处理搜索
const handleSearch = () => {
  pagination.current = 1;
  loadData();
};

// 重置搜索
const resetSearch = () => {
  searchParams.appName = '';
  searchParams.userId = undefined;
  pagination.current = 1;
  loadData();
};

// 编辑应用
const handleEdit = (record: API.AppVO) => {
  router.push(`/app/edit/${record.id}`);
};

// 确认删除应用
const handleDelete = (record: API.AppVO) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除应用 "${record.appName}" 吗？此操作不可恢复。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        // 确保ID以字符串形式处理
        console.log('删除应用ID:', record.id, '类型:', typeof record.id);
        const res = await deleteApp({ id: record.id });
        if (res.data?.code === 0 && res.data?.data) {
          message.success('删除成功');
          loadData();
        } else {
          message.error(res.data?.message || '删除失败');
        }
      } catch (error) {
        console.error('删除应用失败', error);
        message.error('删除应用失败');
      }
    },
  });
};

// 打开设置精选对话框
const openSetFeatured = (record: API.AppVO) => {
  currentApp.value = record;
  priorityForm.priority = record.priority || 0;
  setFeaturedVisible.value = true;
};

// 设置为精选
const handleSetFeatured = async () => {
  if (!currentApp.value) return;
  
  submitLoading.value = true;
  try {
    // 确保ID以字符串形式处理
    console.log('设置应用精选，ID:', currentApp.value.id, '类型:', typeof currentApp.value.id);
    const res = await updateAppByAdmin({
      id: currentApp.value.id,
      priority: priorityForm.priority
    });
    
    if (res.data?.code === 0 && res.data?.data) {
      message.success('设置成功');
      setFeaturedVisible.value = false;
      loadData();
    } else {
      message.error(res.data?.message || '设置失败');
    }
  } catch (error) {
    console.error('设置精选失败', error);
    message.error('设置精选失败');
  } finally {
    submitLoading.value = false;
  }
};

// 查看应用详情
const viewApp = (record: API.AppVO) => {
  // 确保ID以字符串形式传递
  const appId = String(record.id);
  console.log('查看应用详情，ID:', appId, '类型:', typeof appId);
  router.push({
    path: `/chat/${appId}`,
    query: { appName: record.appName }
  });
};

// 表格列定义
const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '应用名称',
    dataIndex: 'appName',
    key: 'appName',
    ellipsis: true,
    customRender: ({ text, record }: { text: string, record: API.AppVO }) => {
      const appNameElement = h('a', {
        onClick: () => viewApp(record)
      }, record.appName);
      
      let tagElement = null;
      if (record.priority && record.priority > 0) {
        tagElement = h(Tag, {
          color: 'gold',
          style: { marginLeft: '8px' }
        }, () => [h(StarFilled), ' 精选']);
      }
      
      return h('div', {}, [appNameElement, tagElement].filter(Boolean));
    }
  },
  {
    title: '提示词',
    dataIndex: 'initPrompt',
    key: 'initPrompt',
    ellipsis: true,
    width: 200,
    customRender: ({ text }: { text: string }) => {
      if (!text) return '-';
      return text.length > 50 ? text.slice(0, 50) + '...' : text;
    }
  },
  {
    title: '创建者',
    dataIndex: 'user',
    key: 'user',
    customRender: ({ record }: { record: API.AppVO }) => {
      return record.user ? record.user.userName : '-';
    },
  },
  {
    title: '部署状态',
    dataIndex: 'deployKey',
    key: 'deployKey',
    customRender: ({ text }: { text: string }) => {
      return text ? h(Tag, { color: 'green' }, () => '已部署') : h(Tag, { color: 'default' }, () => '未部署');
    },
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    customRender: ({ text }: { text: number }) => {
      return text || 0;
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    customRender: ({ text }: { text: string }) => {
      return text ? new Date(text).toLocaleString() : '-';
    },
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    customRender: ({ record }: { record: API.AppVO }) => {
      // 编辑按钮
      const editButton = h(Button, {
        type: 'text',
        size: 'small',
        onClick: () => handleEdit(record)
      }, {
        default: () => h(EditOutlined)
      });
      
      // 设为精选按钮
      const featuredButton = h(Button, {
        type: 'text',
        size: 'small',
        onClick: () => openSetFeatured(record)
      }, {
        default: () => h(StarOutlined)
      });
      
      // 删除按钮
      const deleteButton = h(Button, {
        type: 'text',
        danger: true,
        size: 'small',
        onClick: () => handleDelete(record)
      }, {
        default: () => h(DeleteOutlined)
      });
      
      // 编辑提示
      const editTooltip = h(Tooltip, { title: '编辑' }, {
        default: () => editButton
      });
      
      // 设为精选提示
      const featuredTooltip = h(Tooltip, { title: '设为精选' }, {
        default: () => featuredButton
      });
      
      // 删除提示
      const deleteTooltip = h(Tooltip, { title: '删除' }, {
        default: () => deleteButton
      });
      
      return h(Space, {}, {
        default: () => [editTooltip, featuredTooltip, deleteTooltip]
      });
    },
  },
];
</script>

<template>
  <div class="app-manage-view">
    <Card title="应用管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-container">
        <Form layout="inline">
          <Form.Item label="应用名称">
            <Input
              v-model:value="searchParams.appName"
              placeholder="搜索应用名称"
              allowClear
              style="width: 200px"
              @pressEnter="handleSearch"
            />
          </Form.Item>
          <Form.Item label="用户ID">
            <Input
              v-model:value="searchParams.userId"
              placeholder="用户ID"
              allowClear
              style="width: 120px"
              @pressEnter="handleSearch"
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" @click="handleSearch">
                <template #icon><SearchOutlined /></template>
                搜索
              </Button>
              <Button @click="resetSearch">重置</Button>
            </Space>
          </Form.Item>
        </Form>
      </div>
      
      <!-- 表格区域 -->
      <Table
        :columns="columns"
        :data-source="dataSource"
        :row-key="(record) => record.id"
        :pagination="{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: total,
          showSizeChanger: pagination.showSizeChanger,
          pageSizeOptions: pagination.pageSizeOptions,
          showTotal: (total) => `共 ${total} 条记录`
        }"
        :loading="loading"
        @change="handleTableChange"
        bordered
      />
      
      <!-- 设置精选对话框 -->
      <Modal
        v-model:visible="setFeaturedVisible"
        title="设置应用优先级"
        :confirm-loading="submitLoading"
        @ok="handleSetFeatured"
      >
        <Form ref="formRef" :model="priorityForm" layout="vertical">
          <Form.Item label="应用名称">
            <Input :value="currentApp?.appName" disabled />
          </Form.Item>
          <Form.Item
            label="优先级"
            name="priority"
            extra="设置为99可作为精选应用展示，0为普通应用"
          >
            <Input v-model:value="priorityForm.priority" type="number" :min="0" :max="99" />
          </Form.Item>
        </Form>
      </Modal>
    </Card>
  </div>
</template>

<style scoped>
.app-manage-view {
  width: 100%;
}

.search-container {
  margin-bottom: 16px;
  background-color: #fafafa;
  padding: 16px;
  border-radius: 8px;
}
</style> 